#!/bin/bash
set -e;
# 激活模块
sudo modprobe bcm2835_wdt
# 安装watchdog，并自启服务
sudo apt install watchdog -y;
echo "########## stop service ##########"
sudo systemctl stop watchdog;
echo "########## stop finished ##########"

# 修改配置/boot/config.txt，在后面增加一配置项
# vi可能无法修改，SD卡连接电脑用记事本添加上
echo "######### star config watchdog ##########"
if [ `cat /boot/config.txt|grep "^dtparam=watchdog" ` ];then
	sudo sed -i 's#dtparam=watchdog=.*#dtparam=watchdog=on#g' /boot/config.txt;
else
	sudo sh -c "echo 'dtparam=watchdog=on' >> /boot/config.txt"
fi

# 修改配置文件 /etc/watchdog.conf
# 当1分钟load进程超过24个的时候就会重启
if [ `cat /etc/watchdog.conf|grep "^max-load-1=" ` ];then
    sudo sed -i 's#^max-load-1=.*#max-load-1=24#g' /etc/watchdog.conf;

else
    sudo sh -c "echo 'max-load-1=24' >> /etc/watchdog.conf"
fi

if [ `cat /etc/watchdog.conf|grep "^watchdog-device=" ` ];then
    sudo sed -i 's#^watchdog-device=.*#watchdog-device=/dev/watchdog#g' /etc/watchdog.conf;
else
    sudo sh -c "echo 'watchdog-device=/dev/watchdog' >> /etc/watchdog.conf;"
fi

# 读取温度的位置
if [ `cat /etc/watchdog.conf|grep "^temperature-sensor=" ` ];then
    sudo sed -i 's#^temperature-sensor=.*#temperature-sensor=/sys/class/thermal/thermal_zone0/temp#g' /etc/watchdog.conf;
else
    sudo sh -c "echo 'temperature-sensor=/sys/class/thermal/thermal_zone0/temp' >> /etc/watchdog.conf;"
fi

# 当温度超过80摄氏度的时候就会重启
if [ `cat /etc/watchdog.conf|grep "^max-temperature=" ` ];then
    sudo sed -i 's#^max-temperature=.*#max-temperature=80000#g' /etc/watchdog.conf;
else
    sudo sh -c "echo 'max-temperature=80000' >> /etc/watchdog.conf;"
fi
# watchdog查询硬件周期，太大服务会报错
if [ `cat /etc/watchdog.conf|grep "^watchdog-timeout=" ` ];then
    sudo sed -i 's#^watchdog-timeout=.*#watchdog-timeout=15#g' /etc/watchdog.conf;
else
    sudo sh -c "echo 'watchdog-timeout=15' >> /etc/watchdog.conf;"

fi
echo "########## config finish ##########"
# 重启服务器
echo "########## start service ##########"
sudo systemctl start watchdog;
sudo systemctl enable watchdog;
echo "########## start finished ##########"
